// utils/request.js
const BASE_URL = 'https://client-hoteltool.shengxuankj.com/api'; // 统一的接口前缀

function request(options) {
    return new Promise((resolve, reject) => {
        // ----------- 请求拦截 -----------
        const token = uni.getStorageSync('token');
        if (!token && options.auth) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            reject({ msg: '未登录' });
            return;
        }

        // ----------- 发起请求 -----------
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Content-Type': 'application/json',
                'Token': token || '',
                ...options.header
            },
            success: (res) => {
				console.log('--------------------',res)
                // ----------- 响应拦截 -----------
                if (res.statusCode === 200) {
                    const data = res;
                    if (res.data.code === 1) {
                        resolve(data.data);
                    } else if (res.data.code === 401) {
                        // token 失效处理
                        uni.removeStorageSync('token');
                        uni.showToast({
                            title: '登录已过期，请重新登录',
                            icon: 'none'
                        });
                        resolve(data.data);
                        // reject(data);
                    } else {
                        uni.showToast({
                            title: res.data.msg || '请求错误',
                            icon: 'none'
                        });
                        reject(data);
                    }
                } else {
                    uni.showToast({
                        title: '网络错误',
                        icon: 'none'
                    });
                    reject(res);
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '请求失败',
                    icon: 'none'
                });
                reject(err);
            }
        });
    });
}

// GET 封装
function get(url, params = {}, header = {}, auth = false) {
    return request({
        url,
        method: 'GET',
        data: params,
        header,
        auth
    });
}

// POST 封装
function post(url, data = {}, header = {}, auth = false) {
    return request({
        url,
        method: 'POST',
        data,
        header,
        auth
    });
}

export default {
    get,
    post
};
